//
//  STOSRViewController.swift
//  iPhone
//
//  Created by Toj on 3/7/24.
//

import UIKit

// MARK: - 懒加载(属性), 变量, 初始化init
class STOSRViewController: STBaseViewController {
    
    private let viewModel = STOSRViewModel()
    
    private lazy var tableView: UITableView = {
        let view = UITableView()
        view.backgroundColor = .white
        if #available(iOS 15.0, *) {
            view.sectionHeaderTopPadding = CGFloat.cg_cipher
        }
        view.rowHeight = 44
        view.dataSource = self
        view.delegate = self
        view.contentInset = UIEdgeInsets(top: .nav_barFullHeight, left: 0, bottom: CGFloat.tab_barFullHeight, right: 0)
        view.register(cellClass: VCCell.self)
        view.register(viewClass: MeHeaderView.self)
        view.register(viewClass: UITableViewHeaderFooterView.self)
        
        return view
    }()
}

// MARK: - 生命周期
extension STOSRViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalTo(view)
        }
        
        navigationBar.leftBarView?.isHidden = true
        view.backgroundColor = .white
        viewModel.setupSections {
            self.tableView.reloadData()
        }
    }
}

// MARK: - UITableViewDataSource
extension STOSRViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        let sections = viewModel.classSections
        return sections.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let section = viewModel.classSections[section]
        let cellModels = section.cellModels
        return cellModels.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let section = viewModel.classSections[indexPath.section]
        let cellModels = section.cellModels
        
        let cell = tableView.dequeueReusableCell(withReuseIdentifierClass: VCCell.self)
        // print("-->toj: address:" + cell.cm_objectAddress + ", num:" + String(indexPath.row))
        cell.cellModel = cellModels[indexPath.row]
      
        return cell
    }
}

// MARK: - UITableViewDelegate
extension STOSRViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let model = tableView.cellForItem(at: indexPath, convertTo: VCCell.self)?.cellModel else { return }
        
        guard let cls = UIViewController.vc_reflection(className: model.name) else { return }
        
        CM.begin(time: cls.st_objectName)
        navigationController?.pushViewController(cls, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        let section = viewModel.classSections[section]
        return section.headerSize.height
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let section = viewModel.classSections[section]

        let view = tableView.dequeueReusableHeaderFooterView(withIdentifierClass: MeHeaderView.self)
        view.titleLabel.text = section.title
        
        return view
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = tableView.dequeueReusableHeaderFooterView(withIdentifierClass: UITableViewHeaderFooterView.self)
        return view
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        let section = viewModel.classSections[section]
        return section.footerSize.height
    }
    
    func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
        scrollView.zoomScale
    }
}


/*
//
//  OffScreenRenderedViewController.swift
//  离屏渲染调试
//
//  Created by Toj on 6/16/23.
//

import UIKit
import MetalKit
import CoreGraphics
import GPUImage

// MARK: - 懒加载(属性), 变量, 初始化init
class OffScreenRenderedViewController: STBaseViewController {
    
    private let gdColors = [UIColor.random, UIColor.random]
    private let gdColors2 = [UIColor.random, UIColor.random]

    /* topButton */
    private lazy var cornerButton: UIButton = {
        let view = UIButton()
        view.setTitleColor(.blue, for: .normal)
        view.setTitle("改变", for: .normal)
        view.addTarget(self, action: #selector(didTapCorner), for: .touchUpInside)
        return view
    }()

    /* topButton */
    private lazy var gradientButton: UIButton = {
        let view = UIButton()
        view.setTitleColor(.blue, for: .normal)
        view.setTitle("改变", for: .normal)
        view.addTarget(self, action: #selector(didTapGradient), for: .touchUpInside)
        return view
    }()
    
    /* subView */
    private lazy var cornerSubView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        return view
    }()
    
    /* imageView */
    private lazy var imageView: UIImageView = {
        let view = setupImageView()
        return view
    }()
    /* imageView2 */
    private lazy var imageView2: UIImageView = {
        let view = setupImageView()
        return view
    }()
    /* imageView3 */
    private lazy var imageView3: UIImageView = {
        let view = setupImageView()
        return view
    }()
    
    /* imageView4 */
    private lazy var imageView4: UIImageView = {
        let view = setupImageView()
        return view
    }()
    
    /* imageView5 */
    private lazy var imageView5: UIImageView = {
        let view = setupImageView()
        return view
    }()
    
    /* imageView6 */
    private lazy var imageView6: UIImageView = {
        let view = setupImageView()
        return view
    }()
    
    private let randomColor = UIColor.random
    func setupImageView() -> UIImageView {
        let view = UIImageView()
        view.backgroundColor = randomColor.tt_alpha(0.1)
        return view
    }
    
    /*
     * label
     * 普通的view 设置了 bgColor, 实际上是设置了view上layer 的bgColor,
     * 但是UILabel是设置在了layer的contents上
     */
    private lazy var textLabel: UILabel = {
        let view = UILabel()
        view.textAlignment = .center
        view.text = "小老黑"
        view.backgroundColor = .red
        view.cm_cornerRadius = 10
        return view
    }()
    
    private lazy var cornerView  = setupCornerView()
    private lazy var cornerView2 = setupCornerView()
    private lazy var cornerView3 = setupCornerView()
    private lazy var cornerView4 = setupCornerView()
    private lazy var cornerView5 = setupCornerView()
    private lazy var cornerView6 = setupCornerView()
    
    func setupCornerView() -> UIView {
        let view = UIView()
        view.backgroundColor = .random
        return view
    }
    
    private lazy var corView: UIView = {
        let view = UIButton()
        return view
    }()

    /* discountTipsLabel */
    private lazy var tipsLabel: UILabel = {
        let view = UIInsetLabel()
        view.lbl_contentInsets = UIEdgeInsets(top: 6, left: 16, bottom: 6, right: 16)
        view.numberOfLines = 3
        view.textColor = .white
        view.font = 12.to_systemFont
        view.textAlignment = .center
        view.preferredMaxLayoutWidth = CGFloat.sr_width - 80
        view.backgroundColor = UIColor.red.tt_alpha(0.5)
        view.cm_cornerRadius = 12
        return view
    }()
    
    private let top = 200.to_cgfloat
    private let margin = 10.to_cgfloat
    private let spacing = 10.to_cgfloat
}

// MARK: - 生命周期
extension OffScreenRenderedViewController {
    
    // 支持哪些屏幕方向
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .allButUpsideDown
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        setupMakeAddSubviews()
        setupMakeLayoutSubviews()
        setupMakeContentViews()
    }
}

// MARK: - 点击事件
@objc private extension OffScreenRenderedViewController {
    
    func didTapGradient() {
        gradientButton.isSelected = !gradientButton.isSelected
        tipsLabel.text = "123456789"
    }
 
    func didTapCorner() {
        cornerButton.isSelected = !cornerButton.isSelected
        tipsLabel.text = "iopertyui"
    }
}

// MARK: - 初始化设置
private extension OffScreenRenderedViewController {
    var cls: Int { return 2 }
    var contentViews: [UIView] {
        
        let imageViews = [imageView,  //imageView2, imageView3,
                          //imageView4,
                          imageView5, imageView6]
        
        let cornerViews = [cornerView,  cornerView2, cornerView3,
                           cornerView4, cornerView5, cornerView6
        ]
        let otherViews = [corView, gradientButton, cornerButton]
        
        var views = [UIView]()
//        views.append(contentsOf: otherViews)
//        views.append(contentsOf: cornerViews)
        views.append(contentsOf: imageViews)
        return views
    }
    
    func setupMakeAddSubviews() {
        let views = contentViews
        views.forEach { subview in
            view.addSubview(subview)
        }
        
        view.addSubview(tipsLabel)
        view.addSubview(textLabel)
    }
    
    func setupMakeLayoutSubviews() {
        tipsLabel.snp.makeConstraints { make in
            make.top.equalTo(CGFloat.tab_barFullHeight + 20)
            make.centerX.equalTo(view)
        }
 
        textLabel.snp.makeConstraints { make in
            make.top.equalTo(tipsLabel.snp.bottom).offset(20)
            make.centerX.equalTo(view)
            make.width.greaterThanOrEqualTo(100)
        }
    }
    
    var contentViewsWH: CGFloat {
        let fcls = cls.to_cgfloat
        let wh = (CGFloat.dv_width - spacing * (fcls-1) - margin * 2) / fcls
        return wh
    }
    
    func setupMakeContentViews() {
        
        let views = contentViews
        let wh = contentViewsWH
        var x: CGFloat = 0
        var y: CGFloat = 0
        var index = 0
        views.forEach { subview in
            let rowIndex = index / cls
            let clsIndex = index % cls
            x = margin + (wh + spacing) * CGFloat(clsIndex)
            y = top + (wh + spacing) * CGFloat(rowIndex)
            subview.frame = CGRect(x: x, y: y, width: wh, height: wh)
            view.addSubview(subview)
            index += 1
        }
        
        setupOffScreenRenderedCornerViews()
        setupOffScreenRenderedImageViews()
        setupOffScreenRenderedOthers()
    }
}

extension OffScreenRenderedViewController {
    
    func setupOffScreenRenderedCornerViews() {
        let wh = contentViewsWH
        let wh1_4 = wh * 0.25
        let wh1_2 = wh * 0.5
        // MARK: - cornerView
        cornerView.cm_cornerRadius = wh1_2
        
        // MARK: - cornerView2
        cornerView2.cm_cornerRadius = wh1_2
        
        // MARK: - cornerView3
        cornerView3.backgroundColor = .red
        cornerView3.addSubview(cornerSubView)
        cornerSubView.frame = CGRect(origin: CGPoint(x: wh1_4, y: wh1_4), size: CGSize(width: wh1_2, height: wh1_2))
        cornerSubView.cm_cornerRadius = wh1_4
        
        cornerView3.cm_cornerRadius = wh1_2
        
        // MARK: - cornerView4
        cornerView4.cm_shadow(cornerRadius: wh1_4)
 
        // MARK: - cornerView5
        cornerView5.cm_shadow(cornerRadius: wh1_4)

        // MARK: - cornerView6
        let borderColors = gdColors.map { return $0.cgColor }
        cornerView6.ga_addCorner(radius: 100 * 0.5, border: 3, gradient: borderColors, direction: .vertical)
    }
    
    func setupOffScreenRenderedImageViews() {
        let imageName = "headerImage"
        let image = "headerImage".to_image
        let wh = contentViewsWH
        let radius = wh * 0.5
        let size = CGSize(width: wh, height: wh)
        CM.absoluteTimes {
            print("-->toj: imageView1: ")
            self.imageView.st_corner(radius: radius, named: imageName)
        }
        CM.absoluteTimes {
            print("-->toj: imageView2: ")
            self.imageView2.image = image
            self.imageView2.st_corner = radius
        }
        CM.absoluteTimes {
            print("-->toj: imageView3.1: ")
            self.imageView3.image = image
        }
        CM.absoluteTimes {
            print("-->toj: imageView3: ")
            DispatchQueue.global(qos: .background).async {
                let imageSize = image?.size ?? .zero
                let disFilter = GPUImageSketchFilter()
                disFilter.forceProcessing(at: imageSize)
                disFilter.useNextFrameForImageCapture()
                let stillimageSource = GPUImagePicture(image: image)
                stillimageSource?.addTarget(disFilter)
                stillimageSource?.processImage()
                let newimage = disFilter.imageFromCurrentFramebuffer()?.add_corner(size: size, radius: radius)
                guard newimage != nil else { return }
                DispatchQueue.main.async {
                    self.imageView3.image = newimage
                }
            }
        }
        CM.absoluteTimes {
            print("-->toj: imageView4: ")
            self.imageView4.image = UIImage.gd_image(gradient: gdColors, size: size)?.add_corner(size: size, radius: radius)
        }
        CM.absoluteTimes {
            print("-->toj: imageView5: ")
            //self.imageView5.image = UIImage.gd_image(size: size, gradient: gdColors, radius: radius, borderWidth: 15, borderColor: .random)
            
            self.imageView5.image = UIImage.st_image(size, color: .green, radius: radius, borderWidth: 15, borderColor: .random)
        }
        CM.absoluteTimes {
            print("-->toj: imageView6: ")
            imageView6.backgroundColor = .clear
            
            self.imageView6.image = UIImage.st_image(.green, size: size, radius: radius, borderWidth: 1, borderColor: .red)
        }
    }
    
    func setupOffScreenRenderedOthers() {
        let wh = contentViewsWH
        let radius = wh * 0.5
        let size = CGSize(width: wh, height: wh)
        
        corView.st_shadow()
        
        var norImage = UIImage.gd_image(gradient: gdColors, size: size)
        var selectImage = UIImage.gd_image(gradient: gdColors2, size: size)
        
        gradientButton.setBackgroundImage(norImage, for: .normal)
        gradientButton.setBackgroundImage(selectImage, for: .selected)
        
        norImage = UIImage.gd_image(gradient: gdColors, size: size, radius: radius, borderWidth: 15, borderColor: .random)
        selectImage = UIImage.gd_image(size: size, gradient: gdColors2, radius: radius, borderWidth: 15, borderColor: .random)
        
        cornerButton.setBackgroundImage(norImage, for: .normal)
        cornerButton.setBackgroundImage(selectImage, for: .selected)
    }
}
*/
